package com.oscar.ehome.view.teamview;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.oscar.ehome.R;
import com.oscar.ehome.base.C;
import com.oscar.ehome.base.activity.BasesActivity;
import com.oscar.ehome.bean.setbean.FeedBackBean;
import com.oscar.ehome.bean.setbean.TokenBean;
import com.oscar.ehome.bean.teamBean.TeamListBean;
import com.oscar.ehome.bean.teamBean.UserAppInfoBean;
import com.oscar.ehome.bean.teamBean.UserRoleStaticBean;
import com.oscar.ehome.bean.teamBean.UserStartStaticBean;
import com.oscar.ehome.presenter.BasePresenter;
import com.oscar.ehome.presenter.SetPresenter;
import com.oscar.ehome.presenter.TeamPresenter;
import com.oscar.ehome.provider.gildeimage.GildeUtils;
import com.oscar.ehome.utils.imageview.ChuliPhoto;
import com.oscar.ehome.utils.system.SystemConfigFactory;
import com.oscar.ehome.utils.util.CommonUtils;
import com.oscar.ehome.utils.util.PermissionUtil;
import com.oscar.ehome.utils.util.ToastUtil;
import com.oscar.ehome.utils.util.makeTime;
import com.oscar.ehome.utils.view.MyGridView;
import com.oscar.ehome.utils.view.MyImageView;
import com.oscar.ehome.utils.view.cutimagview.CutImage;
import com.oscar.ehome.view.loginview.LoginActivity;
import com.oscar.ehome.view.setview.view.FeedBackView;
import com.oscar.ehome.view.teamview.adapter.GridviewDetialAdapter;
import com.oscar.ehome.view.teamview.view.MessageInfoView;
import com.oscar.ehome.view.teamview.view.TeamListView;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UploadManager;

import net.tycmc.bulb.androidstandard.utils.JsonUtils;

import org.apache.commons.collections.MapUtils;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

public class TeamDetailActivity extends BasesActivity implements TeamListView, GridviewDetialAdapter.UserDetialIntentListener,
        MessageInfoView, FeedBackView, EasyPermissions.PermissionCallbacks {

    /**
     * 返回
     */
    @BindView(R.id.title_img_back)
    ImageView titleImgBack;
    /**
     * 返回
     */
    @BindView(R.id.title_layout_left)
    RelativeLayout titleLayoutLeft;
    /**
     * 标题
     */
    @BindView(R.id.title_topbar)
    TextView titleTopbar;
    /**
     * 头像
     */
    @BindView(R.id.members_head_img)
    ImageView memberHeadImg;
    /**
     * 姓名
     */
    @BindView(R.id.members_name)
    TextView memberName;
    /**
     * 职级
     */
    @BindView(R.id.members_leve)
    TextView memberLeve;
    /**
     * 性别
     */
    @BindView(R.id.sexs_img)
    ImageView sexImg;
    /**
     * 工号
     */
    @BindView(R.id.team_jobnumber)
    TextView teamJobnumber;
    /**
     * 成员人数
     */
    @BindView(R.id.team_members)
    TextView teamMembers;
    /**
     * 联系电话
     */
    @BindView(R.id.team_phone)
    TextView teamPhone;
    /**
     * 注册时间
     */
    @BindView(R.id.team_registraiontime)
    TextView teamRegistraiontime;
    /**
     * 认证时间
     */
    @BindView(R.id.team_authenticationtime)
    TextView teamAuthenticationtime;
    /**
     * 上次登录
     */
    @BindView(R.id.team_lastlogin)
    TextView teamLastlogin;
    /**
     * 上级头像
     */
    @BindView(R.id.im_detial_boss)
    MyImageView imDetialBoss;
    /**
     * 上级姓名
     */
    @BindView(R.id.tv_detial_bossname)
    TextView tvDetialBossname;
    /**
     * 下级列表
     */
    @BindView(R.id.gv_item_detialmember)
    MyGridView gvItemDetialmember;
    /**
     * 上级
     */
    @BindView(R.id.boss_layout)
    LinearLayout bossLayout;
    /**
     * 下级
     */
    @BindView(R.id.child_layout)
    LinearLayout childLayout;
    /**
     * 星级
     */
    @BindView(R.id.member_leve1)
    ImageView memberLeve1;
    /**
     * 星级
     */
    @BindView(R.id.member_leve2)
    ImageView memberLeve2;
    /**
     * 星级
     */
    @BindView(R.id.member_leve3)
    ImageView memberLeve3;

    @BindView(R.id.headimg_lay)
    RelativeLayout headimgLay;
    /**
     * title布局
     */
    @BindView(R.id.basetitle_bar)
    RelativeLayout basetitleBar;
    /**
     * 修改头像
     */
    @BindView(R.id.xiugai_img)
    LinearLayout xiugai_img;

    @BindView(R.id.lay_all)
    LinearLayout layAll;

    TeamPresenter teamPresenters;
    TeamPresenter teamPresenter;
    SetPresenter setPresenter;
    public GridviewDetialAdapter gridviewDetialAdapter;
    String xia_id = "";//下级ID
    String boss_id = "";//上级ID
    String my_id = "";
    int set = 0;
    public List<UserAppInfoBean.ChildrenBean> children;
    public String photopath = "";//图片地址
    PopupWindows pop;
    String keyname = "";
    String uptoken = "";
    boolean uptokens = true;
    int camera = 0;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_team_detail);
        ButterKnife.bind(this);
        basetitleBar.setBackgroundColor(Color.parseColor(SystemConfigFactory.getInstance(TeamDetailActivity.this).getSystemConfig().getColor()));
        initView();
        initData();
        onClicks();
        //先获取七牛token
        CommonUtils.url_code = 1;
        setPresenter.getUploadToken();
    }

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    /**
     * 初始数据
     */
    private void initView() {
        teamPresenters = new TeamPresenter((MessageInfoView) this);
        teamPresenter = new TeamPresenter((TeamListView) this);
        setPresenter = new SetPresenter(this);

        titleTopbar.setText("个人信息");
        titleImgBack.setVisibility(View.VISIBLE);
        titleImgBack.setImageResource(R.mipmap.fanhui);
        gvItemDetialmember.setFocusable(false);

        xia_id = getIntent().getStringExtra("id");
        set = getIntent().getIntExtra("set", 0);
        if (set == 1) {
            xiugai_img.setVisibility(View.VISIBLE);
        } else {
            xiugai_img.setVisibility(View.INVISIBLE);
        }

        children = new ArrayList<>();
        gridviewDetialAdapter = new GridviewDetialAdapter(TeamDetailActivity.this, children);
        gvItemDetialmember.setAdapter(gridviewDetialAdapter);

    }

    /**
     * 加载下级数据
     */
    public void initData() {
        CommonUtils.url_code = 0;
        teamPresenter.LoadUserAppInfo(SystemConfigFactory.getInstance(this).getSystemConfig().getToken(), xia_id);
        showLoading();
    }

    /**
     * 加载上级数据
     */
    public void initDatas() {
        CommonUtils.url_code = 0;
        teamPresenter.LoadUserAppInfo(SystemConfigFactory.getInstance(this).getSystemConfig().getToken(), boss_id);
        showLoading();
    }

    public void onClicks() {
        gridviewDetialAdapter.setOnIntentClickListener(this);
    }

    @OnClick({R.id.im_detial_boss, R.id.title_layout_left, R.id.headimg_lay, R.id.team_phone})
    public void OnClicked(View view) {
        switch (view.getId()) {
            case R.id.im_detial_boss://上级头像
                my_id = SystemConfigFactory.getInstance(TeamDetailActivity.this).getSystemConfig().getUuid();

                if (!xia_id.equals(my_id)) {//如果这个人的ID和我本人的ID不同，则可以看上级，否则不能看
                    initDatas();
                    xiugai_img.setVisibility(View.VISIBLE);
                    set = 1;
                }
                break;
            case R.id.title_layout_left://返回
                finish();
                break;
            case R.id.headimg_lay:
                if (set == 1) {//更换头像
                    isPressmion();
                    if ("".equals(uptoken)) {
                        CommonUtils.url_code = 1;
                        setPresenter.getUploadToken();
                    }
                    if (!PermissionUtil.getSdPremission(TeamDetailActivity.this) || !PermissionUtil.getCrePremission(TeamDetailActivity.this)) {
                        ToastUtil.show(TeamDetailActivity.this, "请先开启手机读写权限");
                        isPressmion();
                    } else {
                        pop = new PopupWindows(this, layAll);
                        CommonUtils.pay = 2;
                    }
//                        camera = 0;
                }
                break;
            case R.id.team_phone://联系电话
                Intent intent = new Intent(Intent.ACTION_DIAL);
                Uri data = Uri.parse("tel:" + teamPhone.getText().toString());
                intent.setData(data);
                startActivity(intent);
                break;
        }
    }

    @Override
    public void LoadUserTeamAppList(TeamListBean TeamListBean) {

    }

    @Override
    public void getRoalList(TeamListBean TeamListBean) {

    }

    @Override
    public void getStartLeves(TeamListBean TeamListBean) {

    }

    @Override
    public void LoadUserRoleStatisticsAppList(UserRoleStaticBean userRoleStaticBean) {

    }

    @Override
    public void LoadUserStartStatisticsAppList(UserStartStaticBean userRoleStaticBean) {

    }

    /**
     * 个人信息数据
     *
     * @param userAppInfoBean
     */
    @Override
    public void LoadUserAppInfo(UserAppInfoBean userAppInfoBean) {
        dismissLoading();
        if (userAppInfoBean != null && !userAppInfoBean.equals("")) {
//            if (MapUtils.getString(CommonUtils.dakaMap, "s") != null) {
//               // SystemConfigFactory.getInstance(TeamDetailActivity.this).getSystemConfig().setUserMessage(MapUtils.getString(CommonUtils.dakaMap, "s"));
//            }
            children = new ArrayList<>();
            memberName.setText(userAppInfoBean.getName());
            teamPhone.setText(userAppInfoBean.getMobile());
            teamRegistraiontime.setText(userAppInfoBean.getCreateDate());
            teamAuthenticationtime.setText(userAppInfoBean.getAuthenTime());
            teamLastlogin.setText(userAppInfoBean.getLoginDate());
            memberLeve.setText(userAppInfoBean.getRoleMobile().getRoleName());
            if (userAppInfoBean.getRoleMobile().getRoleName() != null) {
                if ("准会员".equals(userAppInfoBean.getRoleMobile().getRoleName())) {
                    teamJobnumber.setText("暂无");
                } else {
                    teamJobnumber.setText(userAppInfoBean.getNo());
                }
            } else {
                teamJobnumber.setText("暂无");
            }
            teamMembers.setText(userAppInfoBean.getAllChildNum());
            children = userAppInfoBean.getChildren();
            if ("女".equals(userAppInfoBean.getSex())) {
                sexImg.setImageResource(R.mipmap.nv);
            } else if ("男".equals(userAppInfoBean.getSex())) {
                sexImg.setImageResource(R.mipmap.nan);
            }

            if (userAppInfoBean.getParent() == null) {
                bossLayout.setVisibility(View.GONE);
            } else {
                bossLayout.setVisibility(View.VISIBLE);
//                GildeUtils.imgLoadPic(TeamDetailActivity.this, C.qiniu + userAppInfoBean.getParent().getPhoto(), imDetialBoss, "net-p");
                GildeUtils.loadUrlImage4(C.qiniu + userAppInfoBean.getParent().getPhoto(), imDetialBoss, TeamDetailActivity.this);
                tvDetialBossname.setText(userAppInfoBean.getParent().getName());
            }

            if (children.size() == 0) {//下级是0时隐藏
                childLayout.setVisibility(View.GONE);
            } else {
                childLayout.setVisibility(View.VISIBLE);
            }

            String img_path = userAppInfoBean.getPhoto();
//            GildeUtils.imgLoadPic(TeamDetailActivity.this, C.qiniu + img_path, memberHeadImg, "net-p");
            GildeUtils.loadUrlImage4(C.qiniu + img_path, memberHeadImg, TeamDetailActivity.this);

            xia_id = userAppInfoBean.getId();
            int seve = userAppInfoBean.getStarLevel();
            switch (seve) {
                case 0:
                    memberLeve1.setImageResource(R.mipmap.xinghui);
                    memberLeve2.setImageResource(R.mipmap.xinghui);
                    memberLeve3.setImageResource(R.mipmap.xinghui);
                    break;
                case 1:
                    memberLeve1.setImageResource(R.mipmap.xing);
                    memberLeve2.setImageResource(R.mipmap.xinghui);
                    memberLeve3.setImageResource(R.mipmap.xinghui);
                    break;
                case 2:
                    memberLeve1.setImageResource(R.mipmap.xing);
                    memberLeve2.setImageResource(R.mipmap.xing);
                    memberLeve3.setImageResource(R.mipmap.xinghui);
                    break;
                case 3:
                    memberLeve1.setImageResource(R.mipmap.xing);
                    memberLeve2.setImageResource(R.mipmap.xing);
                    memberLeve3.setImageResource(R.mipmap.xing);
                    break;
                default:
            }
            gridviewDetialAdapter.setList(children);
        }
    }

    @Override
    public void getUploadToken(TokenBean tokenBean) {
        uptoken = tokenBean.getUptoken();
        if (!uptokens && !"".equals(uptoken)) {
            String filepath = SystemConfigFactory.getInstance(TeamDetailActivity.this).getSystemConfig().getUserimg();
            uploadImageToQiniu(filepath, uptoken);
        }
    }

    @Override
    public void subMitFeed(FeedBackBean feedBackBean) {

    }

    @Override
    public void erroy() {
        dismissLoading();
        ToastUtil.show(TeamDetailActivity.this, getString(R.string.erry));

    }

    @Override
    public void erry(String result) {
        dismissLoading();
        Toast.makeText(TeamDetailActivity.this, result, Toast.LENGTH_SHORT).show();
        if (result.contains("过期")) {
            getSharedPreferences("appbase", Context.MODE_PRIVATE).edit().clear().commit();
            SystemConfigFactory.getInstance(TeamDetailActivity.this).getSystemConfig().SetLogin(false);
            SystemConfigFactory.getInstance(this).getSystemConfig().setIsFirst(true);
            Intent intent = new Intent(TeamDetailActivity.this, LoginActivity.class);
            startActivity(intent);
            finish();
        }
    }

    @Override
    public void onIntentClick(int postion) {
        if (postion == 4) {//跳转进入更多页
            Intent intent = new Intent(TeamDetailActivity.this, TeamListActivity.class);
            intent.putExtra("id", my_id);//个人ID
            intent.putExtra("name", memberName.getText().toString());
            intent.putExtra("chaungtuan", 2);
            intent.putExtra("ids", "");//职级ID
            intent.putExtra("chaun", 2);
            startActivity(intent);
//            finish();
        } else {//进入详情页
            xia_id = children.get(postion).getId();
            initData();
            set = 0;
            xiugai_img.setVisibility(View.INVISIBLE);
        }
    }

    @Override
    public void checkUpImage(String result) {
        Toast.makeText(TeamDetailActivity.this, result, Toast.LENGTH_SHORT).show();

    }

    /**
     * 查看是否是6。0以上系统
     */
    public void isPressmion() {
        String[] perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA};
        if (Build.VERSION.SDK_INT >= 23) {
            if (EasyPermissions.hasPermissions(this, perms)) {//检查是否获取该权限
            } else {
                //第二个参数是被拒绝后再次申请该权限的解释
                //第三个参数是请求码
                //第四个参数是要申请的权限
                EasyPermissions.requestPermissions(this, "ehome将要开启拍照权限！", 0, perms);
            }
        } else {
            EasyPermissions.requestPermissions(this, "ehome将要开启拍照权限！", 0, perms);
        }
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
//        if (camera == 1) {
//            pop = new PopupWindows(this, layAll);
//            camera = 0;
//            CommonUtils.pay = 2;
//        }
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            new AppSettingsDialog.Builder(this, "为了您能使用相机功能，请开启相机权限！")
                    .setTitle("提示")
                    .setPositiveButton("去设置")
                    .setNegativeButton("取消", null)
                    .setRequestCode(0)
                    .build()
                    .show();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }


    /**
     * 拍照弹窗
     *
     * @author mengwanhe
     */
    public class PopupWindows extends PopupWindow {

        public PopupWindows(Context mContext, View parent) {

            final View view = View.inflate(mContext, R.layout.item_popupwindow, null);
            view.startAnimation(AnimationUtils.loadAnimation(mContext, R.anim.fade_ins));
            LinearLayout ll_popup = (LinearLayout) view.findViewById(R.id.ll_popup);
            ll_popup.startAnimation(AnimationUtils.loadAnimation(mContext, R.anim.push_bottom_in_2));

            setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
            setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
            setFocusable(true);
            setOutsideTouchable(true);
            setBackgroundDrawable(new BitmapDrawable());
            setContentView(view);
            showAtLocation(parent, Gravity.BOTTOM, 0, 0);
            if (Build.VERSION.SDK_INT != 24) {
                update();
            }
            LinearLayout lay = (LinearLayout) view.findViewById(R.id.pop_cream);
            Button bt1 = (Button) view.findViewById(R.id.item_popupwindows_camera);// 拍照
            Button bt2 = (Button) view.findViewById(R.id.item_popupwindows_Photo);// 相册
            Button bt3 = (Button) view.findViewById(R.id.item_popupwindows_cancel);// 取消
            lay.setVisibility(View.VISIBLE);
            bt1.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent2 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    intent2.putExtra(MediaStore.EXTRA_OUTPUT,
                            Uri.fromFile(new File(Environment.getExternalStorageDirectory(), "userhead.jpg")));
                    startActivityForResult(intent2, 5);// 采用ForResult打开
                    dismiss();
                }
            });
            bt2.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent();
                    intent.setType("image/*");
                    intent.setAction(Intent.ACTION_GET_CONTENT);
                    startActivityForResult(intent, 6);
                    dismiss();
                }
            });
            bt3.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dismiss();
                }
            });
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == -1 && requestCode == 5) {// 图片 拍照
            int resultCodephoto = 3;
            photopath = ChuliPhoto.getPhotopath();
            Intent intent = new Intent(this, CutImage.class);
            Map<String, Object> intentData = new HashMap<String, Object>();
            intentData.put("photopath", photopath);
            intent.putExtra("intentData", JsonUtils.toJson(intentData));
            startActivityForResult(intent, resultCodephoto);
        }
        if (resultCode == -1 && requestCode == 6) {// 图片 相册中取
            if (data != null) {
                int resultCodephotos = 3;
                String lujing = ChuliPhoto.getPhotoPath(this, data, 1);
                photopath = lujing;
                Intent intents = new Intent(this, CutImage.class);
                Map<String, Object> intentDatas = new HashMap<String, Object>();
                intentDatas.put("photopath", lujing);
                intents.putExtra("intentData", JsonUtils.toJson(intentDatas));
                startActivityForResult(intents, resultCodephotos);
            }
        }
        if (resultCode == 3 && requestCode == 3) {
            String results = data.getExtras().getString("result_photo");
            photopath = results;// 经过处理的图片地址，
            memberHeadImg.setImageBitmap(BitmapFactory.decodeFile(photopath));
            /**
             * 上传服务器代码
             */
            if ("".equals(uptoken)) {
                CommonUtils.url_code = 1;
                setPresenter.getUploadToken();
                uptokens = false;
            } else {
                uploadImageToQiniu(photopath, uptoken);
                showLoading();
            }
        }
    }

    /**
     * 上传图片到七牛
     *
     * @param filePath 要上传的图片路径
     * @param token    在七牛官网上注册的token
     */
    private void uploadImageToQiniu(final String filePath, String token) {
        UploadManager uploadManager = new UploadManager();
        // 设置图片名字
        int v = (int) (Math.random() * (9999 - 1000 + 1)) + 1000;//产生1000-9999的随机数;
        try {
            final String mtime = makeTime.mtime();
            keyname = v + mtime;
        } catch (Exception e) {
            e.printStackTrace();
            dismissLoading();
        }
        uploadManager.put(filePath, keyname, token, new UpCompletionHandler() {
            @Override
            public void complete(String key, ResponseInfo info, JSONObject res) {
                // info.error中包含了错误信息，可打印调试
                // 上传成功后将key值上传到自己的服务器
                if (info.isOK()) {
                    dismissLoading();
                    CommonUtils.url_code = 0;
                    teamPresenters.upLoadImage(SystemConfigFactory.getInstance(TeamDetailActivity.this).getSystemConfig().getToken(), keyname);
                    SystemConfigFactory.getInstance(TeamDetailActivity.this).getSystemConfig().
                            setUserimg(photopath);
                } else {
                    dismissLoading();
                    //如果失败，这里可以把info信息上报自己的服务器，便于后面分析上传错误原因
                    ToastUtil.show(TeamDetailActivity.this, "上传失败");
                }
            }
        }, null);
    }
}
